<?php

namespace App\Utils;

class ApiResponse
{
    /**
     * 成功响应
     *
     * @param mixed $data 返回的数据
     * @param string $message 提示信息
     * @param int $code 状态码
     * @return \Illuminate\Http\JsonResponse
     */
    public static function success($data = null, $message = 'success', $code = 200)
    {
        $response = [
            'code' => $code,
            'message' => $message,
            'data' => $data
        ];

        return response()->json($response, 200);
    }

    /**
     * 失败响应
     *
     * @param string $message 错误信息
     * @param int $code 状态码
     * @param mixed $data 返回的数据
     * @return \Illuminate\Http\JsonResponse
     */
    public static function error($message = 'error', $code = 500, $data = null)
    {
        $response = [
            'code' => $code,
            'message' => $message,
            'data' => $data
        ];

        return response()->json($response, $code == 401 ? 401 : ($code >= 400 && $code < 500 ? 400 : 500));
    }

    /**
     * 分页数据响应
     *
     * @param mixed $data 数据列表
     * @param \Illuminate\Pagination\LengthAwarePaginator $paginator 分页对象
     * @param string $message 提示信息
     * @return \Illuminate\Http\JsonResponse
     */
    public static function paginated($data, $paginator, $message = 'success')
    {
        $response = [
            'code' => 200,
            'message' => $message,
            'data' => $data,
            'pagination' => [
                'total' => $paginator->total(),
                'page' => $paginator->currentPage(),
                'page_size' => $paginator->perPage(),
                'last_page' => $paginator->lastPage()
            ]
        ];

        return response()->json($response);
    }
}